package com.bdsoft.controller;

import java.net.http.HttpRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bdsoft.beanconfig.TokenService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.model.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.bdsoft.domain.QmsQuestion;
import com.bdsoft.service.IQmsQuestionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 问题服务Controller
 * 
 * @author dumingshen
 * @date 2025-10-29
 */
@RestController
@RequestMapping("/quetionService/question")
public class QmsQuestionController extends BaseController
{
    @Autowired
    private IQmsQuestionService qmsQuestionService;

    @Autowired
    private TokenService tokenService;
    /**
     * 查询问题服务列表
     */

    @GetMapping("/list")
    public TableDataInfo list(QmsQuestion qmsQuestion)
    {
        startPage();
        List<QmsQuestion> list = qmsQuestionService.selectQmsQuestionList(qmsQuestion);
        return getDataTable(list);
    }

    /**
     * 获取问题列表
     * @param params
     * @return
     */
    @GetMapping("/QuelistAndType")
    public AjaxResult QuelistAndType(@RequestParam Map<String,Object> params)
    {

        List<Map<String,Object>> list = qmsQuestionService.selectQueList(params);
        return AjaxResult.success(list);
    }
    @GetMapping("/QueHistory")
    public AjaxResult QueHistory(HttpServletRequest httpServletRequest){
        String username=tokenService.getLoginUser(httpServletRequest).getUsername();
        List<Map<String,Object>> list = qmsQuestionService.QueHistory(username);
        Map<Object, Map<String, Object>> qmsIdToMaxTimeMap = new HashMap<>();

        for (Map<String, Object> item : list) {
            Object qmsId = item.get("qms_id");
            Object timeObj = item.get("time");

            if (qmsId == null || timeObj == null) {
                continue; // 如果 qms_id 或 time 为空，跳过该条
            }

            // 当前 qms_id 已存在，则比较 time，保留较大的
            if (qmsIdToMaxTimeMap.containsKey(qmsId)) {
                Map<String, Object> existing = qmsIdToMaxTimeMap.get(qmsId);
                Object existingTime = existing.get("time");

                // 比较 time 字符串（格式 yyyy-MM-dd，直接字符串比较即可）
                if (timeObj instanceof String && existingTime instanceof String) {
                    String currentTime = (String) timeObj;
                    String existingTimeStr = (String) existingTime;

                    if (currentTime.compareTo(existingTimeStr) > 0) {
                        // 当前时间更大，更新
                        qmsIdToMaxTimeMap.put(qmsId, item);
                    }
                    // 如果相等，保留原有的（也可以选择保留当前的，这里保留原有的）
                }
            } else {
                // 第一次见到这个 qms_id，直接放入
                qmsIdToMaxTimeMap.put(qmsId, item);
            }
        }

        // ✅ 最终结果：List<Map<String, Object>>，每个 qms_id 只出现一次，且 time 最大
        List<Map<String, Object>> result = new ArrayList<>(qmsIdToMaxTimeMap.values());

        return AjaxResult.success(result);
    }

    /**
     * 导出问题服务列表
     */

    @Log(title = "问题服务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QmsQuestion qmsQuestion)
    {
        List<QmsQuestion> list = qmsQuestionService.selectQmsQuestionList(qmsQuestion);
        ExcelUtil<QmsQuestion> util = new ExcelUtil<QmsQuestion>(QmsQuestion.class);
        util.exportExcel(response, list, "问题服务数据");
    }

    /**
     * 获取问题服务详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id, HttpServletRequest httpRequest)
    {
        LoginUser loginUser=tokenService.getLoginUser(httpRequest);
        return success(qmsQuestionService.selectQmsQuestionById(loginUser.getUsername(),id));
    }

    /**
     * 新增问题服务
     */

    @Log(title = "问题服务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QmsQuestion qmsQuestion)
    {
        return toAjax(qmsQuestionService.insertQmsQuestion(qmsQuestion));
    }

    /**
     * 修改问题服务
     */

    @Log(title = "问题服务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QmsQuestion qmsQuestion)
    {
        return toAjax(qmsQuestionService.updateQmsQuestion(qmsQuestion));
    }

    /**
     * 删除问题服务
     */
    @PreAuthorize("@ss.hasPermi('quetionService:question:remove')")
    @Log(title = "问题服务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(qmsQuestionService.deleteQmsQuestionByIds(ids));
    }
}
